var dao = require("../dao/dao")
var payback_dao = require("../dao/pay_fee_dao")
var mark_dao = require('../dao/mark_dao');
var log = require("./../../util/loginfo").getInstand;
var gameInfo = require('./game').getInstand;

var payback_api = {};

payback_api.getPayBackFeeList = function(info,callback){

	var sql;
	if (info.beginTime == "" && info.endTime == "") {
		sql = "select * from recharge_back_fee where aid = " + info.uid;
	} else if (info.beginTime >= info.endTime) {
		callback('{"status":1,"msg":"开始时间必须小于结束时间！","data":[]');
		return;
	} else {
		sql = "select * from recharge_back_fee where aid = " + info.uid + " and log_time >= " + info.beginTime + " and log_time <= " + info.endTime;
	}
	payback_dao.getMyBackFeeRecord(sql, function(state, RusultData){
		if (state){
			var string = '{"status":0,"msg":"","data":[';
			for (var i = 0; i < RusultData.length; i++) {
				string += '{"uid":' + RusultData[i].aid + ',"origin_fee":"' + RusultData[i].origin_fee 
				+ '","add_fee":' + RusultData[i].add_fee + ',"current_fee":' + RusultData[i].current_fee 
				+ ',"log_time":' + RusultData[i].log_time + '}';
				if (i != RusultData.length - 1)
					string += ',';
			}
			string += ']}';
			sendStr = string;
			callback(sendStr);
		}
		else{
			callback('{"status":1,"msg":"获取充值返利记录失败！","data":[]');
		}
	})
}

payback_api.calAgentFee = function(){
	mark_dao.getPayRecord(function(state,rows1){
		if (state == 0) {
			return;
		}
		for (var x in rows1) { //多少条订单需要计算返佣金
			payback_dao.getAgentLevelById(rows1[x].userId, function(state, rows2){
				if (state == 0) {

					//将订单已处理返利标注状态 ispaybackfee为-1 不需要返利
					mark_dao.setBackFeeStatus(rows1[x].id, -1, function(state){
						if (state) {
							log.info(rows1[x].userId, " no need pay back fee! ");
						}
					});

					return;
				}
				log.info("uid == " + rows1[x].userId + " fee == " + rows1[x].useCoin);
				for (var y in rows2) {
					calSingleAgentFee(x, rows1, y, rows2);
				}
			});
		}
	});
}

function calSingleAgentFee(x, rows1, y, rows2) {
    var fee = rows1[x].useCoin * 100 / 10000 / (parseInt(y)+1);
    log.info("aid == " + rows2[y].aid + " fee == " + fee);

    var r_userInfo = {
        sendUserId: rows2[y].aid,
        sendCoin: fee,
        change_type: 1,
        diamond: 0
    };
    new Promise(function (resolve, reject) {
        gameInfo.GameBalance(r_userInfo, function(state){
            if (state) {
                log.info("success save aid == " + rows2[y].aid + "id == " + rows1[x].id);
                resolve(1);
            } else {
                reject(0);
            }
        });
    }).then(function (value) {
        log.info(value)
        //将订单已处理返利标注状态 ispaybackfee为1 
        mark_dao.setBackFeeStatus(rows1[x].id, 1, function(state){
            if (state) {
                //存储及发送邮件
                log.info("success and send email! aid == " + rows2[y].aid);
            }
        });
    }).then(function (value) {
        log.info(value)
        payback_dao.getBackFeeRecord(rows2[y].aid,function(state, rows3){
            log.info("getBackFeeRecord ");
            var curFee = fee;
            var originFee = 0; 
            if (state == 1 && rows3) {
                curFee = curFee + rows3[0].current_fee;
                originFee = rows3[0].current_fee;
            }
            
            payback_dao.saveBackFeeRecord(rows1[x].userId, rows2[y].aid, rows1[x].useCoin, originFee, fee, curFee, function(state, insertId){
                if (state) {
                    log.info("success save2");

                    let emailInfo = {
                        isread: 0,
                        title: "【系统消息】下级代理["+rows1[x].userId+"]给您返利"+fee,
                        type: 999,
                        otherId: insertId,
                        userid: rows2[y].aid,
                        sendid: rows1[x].userId,
                    };
                    dao.saveEmail(emailInfo);
                }
            });
        });
    }).catch(function (err) {
        log.err(err);
    });
}

module.exports = payback_api;



